﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Cnblogs.Service;

namespace Cnblogs
{
    public partial class SearchPage : PhoneApplicationPage
    {
        private bool isRequesting = false;
        public SearchPage()
        {
            InitializeComponent();
        }

        private void ptbSearch_ActionIconTapped(object sender, EventArgs e)
        {
            DoSearch(ptbSearch.Text.Trim());
        }
        private void ptbSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                DoSearch(ptbSearch.Text.Trim());
            }
        }

        private void DoSearch(string key)
        {
            this.Focus();
            if (isRequesting)
            {
                return;
            }
            isRequesting = true;
            GlobalIndicator.Instance.StartBusy("搜索中...");
            FeedService.Request(ServiceType.Search, new NewsData { Key = key }, (obj, isSuccess) =>
            {
                GlobalIndicator.Instance.StopBusy();
                isRequesting = false;
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    if (isSuccess && obj != null)
                    {
                        lbx_bloggers.ItemsSource = null;
                        lbx_bloggers.ItemsSource = (obj as SearchBloggerFeed).Items;
                    }
                });
            });
        }

        private void btn_user_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            if (btn != null)
            {
                var user = btn.DataContext as SearchBlogger;
                if (user != null)
                {
                    NavigationService.Navigate(new Uri(Constants.P_BloggerPage + "?blogapp=" + user.BlogApp + "&name=" + user.Title, UriKind.Relative));
                }
            }
        }
    }
}